from association_rule import Item_Factory, data_manager, FPminer, Analyser, Setting, Cli
import csv
import sys

if (sys.version_info.major < 3) or (sys.version_info.minor < 9):
    print(f'当前python版本为{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}, 请使用版本号大于3.9.7的python')
    input('按回车键退出...')
    quit()
elif (sys.version_info.major == 3) and (sys.version_info.minor == 9) and (sys.version_info.micro < 7):
    print(f'当前python版本为{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}, 请使用版本号大于3.9.7的python')
    input('按回车键退出...')
    quit()

try:
    import scipy
except:
    print('检测到未安装scipy库, 故将采用查表插值法计算卡方检验的p值\n经验算,chi2在[e^-10, \u221e)区间内p误差小于2.5e-4,区间外p误差小于2.6e-3;\n如对p值有精度要求, 请安装scipy或使用外部工具直接计算卡方值对应的p值')

cli = Cli()
try:
    setting = Setting()
except Exception as err:
    print(repr(err))

file_parsed = False
while not file_parsed:
    try:
        file_path = cli.get_file_path()
        try:
            setting.setting_file_path(file_path)
        except Exception as err:
            print(err)
            break
        file_data = cli.get_file_data(file_path, setting.coding)
        setting.setting_data_width(len(file_data[0]))
        print('文件前2行预览...')
        for i in range(2):
            print(f'第{i + 1}行: {file_data[i]}')
        file_parsed = True
    except Exception as err:
        print(err)
        print('文件导入失败, 请重新导入csv')

try:
    print('初始化...')
    item_factory = Item_Factory()
    tagger = data_manager.Tagger().set_index_tags_map(setting.index_tags_map)
    data_assistant = data_manager.Data_Assistant()
    if setting.absolute_name_map_file.exists():
        data_assistant.read_name_map(setting, tagger)
    else:
        print('正在生成映射表...')
        if setting.has_head:
            data_assistant.form_name_map(file_data[1: ], setting)
        else:
            data_assistant.form_name_map(file_data, setting)
        print(f'已将映射表生成在{setting.absolute_name_map_file}, 请先完成名称映射')
        input('按回车键退出...')
        quit()

    if setting.has_head:
        analyze_data = data_assistant.form_data(file_data[1: ], item_factory, tagger, setting)
    else:
        analyze_data = data_assistant.form_data(file_data, item_factory, tagger, setting)
    fpminer = FPminer(analyze_data, support=setting.support, threshold=setting.threshold)
    print('开始频繁模式挖掘, 可能费时较长, 请耐心等候...')
    frequent_patterns = fpminer.get_frequent_patterns()
    print('完成频繁模式挖掘, 开始分析频繁模式, 可能费时较长, 请耐心等候...')
    analyzer = Analyser(frequent_patterns, data_assistant, setting.internal_analysis_settings, setting.external_analysis_settings)
    analyzer.run()
    print('完成频繁模式分析, 输出结果中...')
    setting.absolute_result_dir.mkdir()
    with setting.absolute_result_dir.joinpath('internal.csv').open('w+', encoding='utf-8-sig', newline='') as f:
        writer = csv.writer(f)
        writer.writerows([analyzer.internal_header] + analyzer.internal_results)
    with setting.absolute_result_dir.joinpath('external.csv').open('w+', encoding='utf-8-sig', newline='') as f:
        writer = csv.writer(f)
        writer.writerows([analyzer.external_header] + analyzer.external_results)
    print('完成!')
except Exception as err:
    print(f'出现错误:{repr(err)}')

input('按回车键退出...')